package edu.gdut.tiantian.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;

import edu.gdut.tiantian.entity.Category;
import edu.gdut.tiantian.service.Impl.CategoryService;

@Controller
@RequestMapping("/category")
public class CategoryController {
	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping("/findById.do")
	public ModelAndView findById(Integer categoryId) {
		ModelAndView mv = new ModelAndView();
		Category category = categoryService.findById(categoryId);
		mv.addObject("category",category);
		mv.setViewName("background/category-show");
		return mv;
	}
	
	@RequestMapping("/update.do")
	public String update(Category category) {
		categoryService.updateCategory(category);
		return "redirect:/category/findAll.do?pageNum=0";
	}
	
	@RequestMapping("/delete.do")
	public String delete(Integer categoryId) {
		categoryService.delCategory(categoryId);
		return "redirect:/category/findAll.do?pageNum=0";
	}
	
	@RequestMapping("/save.do")
	public String save(Category category) {
		categoryService.saveCategory(category);
		return "redirect:/category/findAll.do?pageNum=0";
	}
	
	@RequestMapping("/findAll.do")
	public ModelAndView findByCondition(Integer pageNum, HttpServletRequest req) {
		Map<String, String> condition = new HashMap<>();
		Enumeration<String> paramNames = req.getParameterNames();
		StringBuffer conditionStr = new StringBuffer();
		while(paramNames.hasMoreElements()) {
			String key = paramNames.nextElement();
			String value = req.getParameter(key);
			if(value != null && value.trim().length() !=0) {
				condition.put(key, value);
				conditionStr.append("&"+key+"="+value);
			}
		}
		ModelAndView mv = new ModelAndView();
		List<Category> categoryList = categoryService.findByCondition(condition,pageNum,5);
		PageInfo<Category> pageInfo = new PageInfo<Category>(categoryList);
		mv.addObject("condition",conditionStr);
		mv.addObject("pageInfo",pageInfo);
		mv.setViewName("background/category-manager");
		return mv; 
	} 
	 
}
